package com.vietnam.power.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.vietnam.power.constant.AppConfigurationConstant;
import com.vietnam.power.constant.GeneralConstant;
import com.vietnam.power.domain.Article;
import com.vietnam.power.domain.ArticleSearchCriteria;
import com.vietnam.power.domain.MessageInfo;
import com.vietnam.power.domain.UserInfo;
import com.vietnam.power.service.ArticleService;
import com.vietnam.power.service.MessageService;
import com.vietnam.power.service.UserService;
import com.vietnam.power.util.MessageUtil;

@Controller(value = "adminCommonController")
public class CommonController {
	
	private static Logger logger = Logger.getLogger(CommonController.class);
	
	@Autowired
	private MessageSource messageSource;

	@Autowired
	private UserService userService;

	@Autowired
	private VelocityEngine velocityEngine;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private ArticleService articleService;

	@RequestMapping(value = "/forgotPassword", method = RequestMethod.GET)
	public ModelAndView forgotPassword() {
		ModelAndView mav = new ModelAndView("admin/forgotPassword");
		mav.addObject("pageTitle", messageSource.getMessage("admin.login.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = "/forgotPassword", method = RequestMethod.POST)
	public String forgotPassword(HttpServletRequest request, @RequestParam(value = "username", required = true) String username) {
		String messageCode = StringUtils.EMPTY;

		// check user id
		UserInfo userInfo = userService.getUserByUserName(username);

		if (userInfo.getUserName() == null) {
			messageCode = "admin.login.userid.invalid";
		} else {
			String newPassword = String.valueOf(System.currentTimeMillis());
			logger.debug("new password: " + newPassword);
			messageCode = "admin.user.login.form.forget.password.send.email";

			Map model = new HashMap();
			model.put("username", userInfo.getFirstName() + " " + userInfo.getLastName());
			model.put("newPassword", newPassword);
			String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/forgotPassword.vm", "UTF-8", model);
			//update password
			userInfo.setPassword(newPassword);
			userService.changePassword(userInfo);
			//create email
			ArticleSearchCriteria asc = new ArticleSearchCriteria();
			asc.setArticleGroupName(AppConfigurationConstant.ARTICLE_GROUP.CONTACT);
			List<Article> artList = articleService.getArticleListByGroupName(asc, null);
			if (CollectionUtils.isNotEmpty(artList)) {
				String email = artList.get(0).getEmail();
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setFrom(email);
				messageInfo.setTo(userInfo.getEmail());
				String subject = messageSource.getMessage("admin.email.forgot.password", null, LocaleContextHolder.getLocale());
				messageInfo.setSubject(subject);
				messageInfo.setContent(content);
				
				messageService.createEmail(messageInfo);
				
				request.setAttribute("message", messageSource.getMessage(messageCode, null, LocaleContextHolder.getLocale()) + userInfo.getEmail());
				request.setAttribute("pageTitle", messageSource.getMessage("admin.login.title", null, LocaleContextHolder.getLocale()));
				return "admin/sendForgotEmail";
			}
		}

		if (StringUtils.isNotBlank(messageCode)) {
			request.setAttribute("message", messageSource.getMessage(messageCode, null, LocaleContextHolder.getLocale()));
		}

		request.setAttribute("pageTitle", messageSource.getMessage("admin.login.title", null, LocaleContextHolder.getLocale()));
		return "admin/forgotPassword";

	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false, value = "authfailed") String authfailed) {

		ModelAndView mav = new ModelAndView("admin/login");
		String messageCode = StringUtils.EMPTY;
		if (authfailed != null) {
			Exception e = (Exception) request.getSession().getAttribute(GeneralConstant.SPRING_SECURITY_LAST_EXCEPTION);
			messageCode = MessageUtil.getLoginErrorMessage(e);
		}

		// remove all session when back to login
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.invalidate();
		}

		if (StringUtils.isNotBlank(messageCode)) {
			mav.addObject("message", messageSource.getMessage(messageCode, null, LocaleContextHolder.getLocale()));
		}
		mav.addObject("pageTitle", messageSource.getMessage("admin.login.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/admin/goHomePage" }, method = RequestMethod.GET)
	public ModelAndView goHomePage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("admin/homepage");

		mav.addObject("pageTitle", messageSource.getMessage("admin.homepage.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

}
